#define DEBUG_MEMORY_LEAKS 0
#define PAUSE_AT_END       0

#if DEBUG_MEMORY_LEAKS==1
    #include <crtdbg.h>
#endif

#include <iostream>
#include <fstream>
#include "ParseHelper.h"
#include "Driver.h"
#include "InterpreterVisitor.h"
#include "CompilerVisitor.h"
#include "Util.h"

int main(int argc, char* argv[])
{
    #if DEBUG_MEMORY_LEAKS==1
    {
    #endif

        if(argc != 2)
        {
            cout << "Pouziti: compiler zdrojovy-soubor" << endl;

            #if PAUSE_AT_END==1
                system("pause");
            #endif

            return 1;
        }

        string lInputFilename = string(argv[1]);
        string lOutputFilename = lInputFilename + ".bin";

        ParseHelper lHelper;
        RUN::Driver lDriver(lHelper);

        bool lResult = lDriver.parse_file(lInputFilename);

        if(lResult)
        {
            try
            {
                lHelper.DoBasicSemanticChecks();

                /*
                pokud by se delala interpretace AST, tak tady toto odkomentovat
                InterpreterVisitor lInterpreter(lHelper.GetEntryPoint());
                lInterpreter.Run();
                */

                CompilerVisitor lCompiler(lHelper);

                // binary je dulezite, aby se napr. nenahrazovalo 0A za 0D 0A
                ofstream lOutput(lOutputFilename.c_str(), ios_base::binary);
                lCompiler.Serialize(lOutput);
                lOutput.close();
            }
            catch(std::exception& e)
            {
                cout << e.what() << endl;
            }
        }
        else
        {
            cout << "Chyba pri parsovani." << endl;
        }

    #if DEBUG_MEMORY_LEAKS==1
    }
    #endif

    #if DEBUG_MEMORY_LEAKS==1
        _CrtDumpMemoryLeaks();
    #endif

    #if PAUSE_AT_END==1
        system("pause");
    #endif
}
